package island.gotenyama.wand.validation;

import island.gotenyama.wand.annotation.FieldDefinition;
import island.gotenyama.wand.annotation.TimestampPattern;
import island.gotenyama.wand.bean.AField;
import island.gotenyama.wand.bean.MessageKey;
import island.gotenyama.wand.exception.FatalException;
import island.gotenyama.wand.utils.AppsDateUtils;

import org.springframework.stereotype.Component;

/**
 * を検証する。
 * 
 * @author tkawabata
 */
@Component
public class TimestampPatternValidation extends AValidation {

	/**
	 * エラーコード
	 */
	public static final String errorCode = "input.error.regex";

	@Override
	public boolean isValid(Object entry, Object... params) {
		if (entry == null) {
			return true;
		}
		if (params == null || params.length < 1) {
			throw new FatalException("Pattern is Null.");
		}
		String pattern = params[0].toString();
		// TODO USE REGEX
		try {
			AppsDateUtils.toDate(entry.toString(), pattern);
		} catch (FatalException e) {
			return false;
		}
		return true;
	}

	@Override
	public MessageKey validate(AField aField, Object entry) {
		if (aField == null) {
			throw new FatalException("NULLのため、検証できない。");
		}
		TimestampPattern timestampPattern = aField.getField().getAnnotation(TimestampPattern.class);
		String pattern = timestampPattern.pattern();
		if (isValid(entry, pattern)) {
			return null;
		} else {
			FieldDefinition fieldDef = aField.getFieldDefinition();
			return new MessageKey(errorCode, fieldDef.name(), fieldDef.nameJp(), pattern);
		}
	}
}
